package com.domain;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class PageResult<T> implements Serializable {
    // 数据列表
    private List<T> records;

    //总记录数
    private long total;

    //总页数
    private long pages;

    public static <VO,PO> PageResult<VO> of (Page<PO> p, Class<VO> tClass){
        PageResult<VO> pageResult = new PageResult<>();
        pageResult.setTotal(p.getTotal());
        pageResult.setPages(p.getPages());
        List<PO> records = p.getRecords();
        if(CollUtil.isEmpty(records)){
            pageResult.setRecords(Collections.emptyList());
            return pageResult;
        }
        pageResult.setRecords(BeanUtil.copyToList(records,tClass));
        return pageResult;
    }

    public static <VO,PO> PageResult<VO> of (Page<PO> p, Function<PO,VO> convertor){
        PageResult<VO> pageResult = new PageResult<>();
        pageResult.setTotal(p.getTotal());
        pageResult.setPages(p.getPages());
        List<PO> records = p.getRecords();
        if(CollUtil.isEmpty(records)){
            pageResult.setRecords(Collections.emptyList());
            return pageResult;
        }
        pageResult.setRecords(records.stream().map(convertor).collect(Collectors.toList()));
        return pageResult;
    }
}
